//成品
var app_url = location.origin;
 var MANAGE_MODE=false;
 var TEAM=0;
 var PlaceOrder=false;//代下单
 var RATE=Number($.cookie('InlaySettingsRate'));//汇率
var orderingID=getUrlParam('cid');//代下单的客户id
var indexCount=1;
var ends=true;
var loads=true;
(function () {

    var inlaysettings = {
        init: function () {
        	args = GetUrlParms();
            // localStorage.removeItem('das');
			if(args["team"]!=undefined){						
				 TEAM = args["team"];//产品ID
			}
			if(args["cid"]!=undefined){						
				 Customer_id = args["cid"];	
				 PlaceOrder=true;//代下单
			}

            this.bindEvents();

			//筛选条件
             loadInlays();
        },
        bindEvents: function () { 
            var self = this;

            //筛选
            $("#term_app_btn").on("click",function(){
            	if(PlaceOrder==true){
            		location.href="/Customer/InlaySettingsFilter?team=3&cid="+Customer_id+'&userName='+NullFormat(getUrlParam('userName'));
            	}else{
            		location.href="/Customer/InlaySettingsFilter?team="+TEAM;
            	}
            });
            //点击进入产品详情
           	$("#inlaysettings").on("click","#app_link_item",function(){
                var das={
                    productno :$(this).parent().attr('data-productno'),
                    productsupplier :$(this).parent().attr('data-productsupplier')
                };
           		var link_url=$(this).attr("data-src");
           		if(APP){
           			var appJson={};
           			appJson.title="空托详情";
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));

           			YiYi_APP.setProductInfo(JSON.stringify(das));

           		}else{
                    window.sessionStorage.das = JSON.stringify(das);
           			location.href=link_url;
           		}        		
           });
            //点击菜单
			$("#show_menu_btn").on("click",function(){
				$("#assistant_menu_box").toggle();
			});
			//关闭菜单
			$("#assistant_menu_box").on("click",function(){
				$("#assistant_menu_box").hide();
			});
           //新增
			$("#add_btn").on("click",function(){
				var link_url="/Team/InlaySettingsManagement?type=7";
				if(APP){
					var appJson={};
           			appJson.title="空托新增";
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
				}else{
					location.href=link_url;
				}
			});

        },


    };
    inlaysettings.init();
    
})();

//加载数据
function loadInlays(pageIndex,pageSize) {
    indexCount++;
    pageIndex=pageIndex?pageIndex:1;
    var self = this;
    if(pageIndex == 1){
        myApp.showIndicator();//显示加载中
    }
    loads=false;
    if(APP){
        $(".footer_box").hide();
    }
    var params = PARAMS;//APP手机过来的参数
    if(params==null){
        params={};
    }
    if(TEAM==2){
        params.IsMyStock=true;//现货
    }else{
        params.OnShelves = 1;
    }
    if(TEAM==0){
        params.CustomerID = CustomerID;//客户ID
    }
    if(TEAM==3){
        params.UserID=UserID;
        params.CustomerID = orderingID;
    }
    params.useDict = true;
    params.pageSize = pageSize?pageSize:50;
    params.pageIndex = pageIndex;
    params.limit=pageSize?pageSize:50;
    params.GoodsType=7;
    var params = JSON.stringify(params);
    var url ="/Team/GetProductData";
    $.ajax({
        url: url,
        data: params,
        type: "POST",
        contentType: "application/json; charset=utf8",
        timeout: 30000, //超时时间：30秒
        success: function (result) {
            myApp.hideIndicator();
            clearProductBtn(); //清空选项
            tempSupplier = 0;
            var res=eval('(' + result + ')')
            if (res.msgcode == true) {
                window.GOODS_ITEMS = res.msginfo.rows;
                var dtRenderStart = new Date().getTime();
                isSearching = false;
                if (res.msginfo.rows.length == 0) {
                    if(JSON.parse(params).pageIndex!=1){
                        ends=false;
                        $('#endload').text('已全部加载完毕');
                    }else {
                        ends=true;
                        $('#endload').text('');
                        $("#inlaysettings").html('<div class="no_data_tip" style="color:red">没有符合条件的结果</div>');
                    }

                } else {
                    if(res.msginfo.rows.length>0&&res.msginfo.rows.length<50){
                        ends=false;
                        $('#endload').text('已全部加载完毕')
                    }
                        var inlaysettings = [];
                    for (var i = 0; i < res.msginfo.rows.length; i++) {
                        var row = res.msginfo.rows[i];

                        var totalPrice = (parseFloat(row.GoldPrice) * parseFloat(row.NetGoldWeight) * (1 + parseFloat(row.Wastage))) + parseFloat(row.SidePrice) + parseFloat(row.LaborFee) + parseFloat(row.Insurance) + parseFloat(row.SideLaborFee * row.SideNum)    //金价*总重*（1+损耗）+副石金额+工费+保险费+副石工费*副石数

                        inlaysettings.push(
                            '<li data="', row.Supplier, '" itemtype="" itemid="', row.ID, '"  data-ProductNo="', row.OriginSN, '"  data-ProductSupplier="', row.Supplier, '" class="', i % 2 == 0 ? "" : "mark", '">'
                        )
                        if (TEAM == 1 || TEAM == 2) {
                            inlaysettings.push(
                                '<a href="#" data-src=', "/", "Team/InlaySettingsDetails/?ID=", row.ID, "&team=", TEAM, PlaceOrder ? "&cid=" + Customer_id : "","&styleNo=", row.StyleNo, ' id="app_link_item"  data-type="' + GetCategory("inlaysettings", 1) + '">'
                            )
                        } else if (TEAM == 3) {
                            inlaysettings.push(
                                '<a href="#" data-src=', "/", "Team/InlaySettingsDetails/?ID=", row.ID, "&team=", TEAM, PlaceOrder ? "&cid=" + Customer_id : "", "&userName=", getUrlParam('userName'), "&styleNo=", row.StyleNo, ' id="app_link_item"  data-type="' + GetCategory("inlaysettings", 1) + '">'
                            )
                        } else {
                            inlaysettings.push(
                                '<a href="#" data-src=', "/", "Customer/InlaySettingsDetails/?ID=", row.ID, "&team=", TEAM, "&typeNo=", 1, "&styleNo=", row.StyleNo, PlaceOrder ? "&cid=" + Customer_id : "", ' id="app_link_item"  data-type="' + GetCategory("inlaysettings", 1) + '">'
                            )
                        }
                        inlaysettings.push(
                            '<div class="image_app_box">',
                            '<img style="" class="product_img lazy" data-src="', imgSrc(row.Images), '" src="' + imgSrc(row.Images) + '" alt="空托" />',
                            '<div class="stock_img_box">', isStockImg(row.IsStock), '</div>',
                            '</div>'
                        )
                        inlaysettings.push(
                            '<div class="product_data">',
                            '<h4>'
                        );

                        inlaysettings.push(
                            '<span><b style="font-size:0.5rem" title="系列名称">' + row.Series + '</b></span>'
                        );

                        if (TEAM == 0) {
                            if (RMBInlaySettingsPrice_td_new == true) {
                                inlaysettings.push(
                                    '<span class="CurrentRMB"><b style="font-size:0.5rem">￥</b><b title="人民币价格">' + formatRMBPrice(row.Price) + '</b></span>'
                                );
                            }

                        } else {
                            if (TEAM == 3) {
                                if (menu_ordering_inlaysettings_ConfirmPrice || RoleID ==1) {
                                    inlaysettings.push(
                                        '<span class="CurrentRMB"><b style="font-size:0.5rem">￥</b><b title="人民币价格">' + formatRMBPrice(row.Price) + '</b></span>'
                                    );
                                }
                            } else {
                                if (menu_ordering_inlaysettings_ConfirmPrice || RoleID ==1) {
                                    inlaysettings.push(
                                        '<span class="CurrentRMB"><b style="font-size:0.5rem">￥</b><b title="人民币价格">' + formatRMBPrice(totalPrice) + '</b></span>'
                                    );
                                }
                            }

                        }

                        inlaysettings.push(
                            '</h4>'
                        );

                        var dataLaborFee = ""; //工费
                        var dataWastage = "";  //损耗
                        if (TEAM == 0 || TEAM == 3) {
                            dataLaborFee = parseFloat(row.CustomerLaborFee);
                            dataWastage = parseFloat((row.CustomerWastage * 100).toFixed(0))
                        } else {
                            dataLaborFee = parseFloat(row.LaborFee);
                            dataWastage = parseFloat((row.Wastage * 100).toFixed(0))
                        }

                        inlaysettings.push(
                            '<div class="data_box"><div class="product_div_bg" style="padding-left: 2px">' +
                            '<b class="flex_b1" title="厂家">厂家:<span style="font-size:0.6rem;color:#fa8e00">' + row.Manufactor + '</span></b>' +
                            '<b class="flex_b2"  title="工艺">工费:<span style="font-size:0.6rem;color:#fa8e00">' + dataLaborFee + '</span></b>' +
                            '<b class="flex_b3"  title="损耗">损耗:<span style="font-size:0.6rem;color:#fa8e00">' + dataWastage + '%</span></b>' +
                            '</div>' +
                            '<div class="product_div_bg product_bg" >' +
                            '<b class="product_b" title="总重">' + row.TotalWeight + 'g' + '</b>' +
                            '<b class="product_b" title="主石重">' + row.MainWeight + 'Ct' + '</b>' +
                            '<b class="product_b" title="尺寸">' + row.Measurement + '</b>' +
                            '</div></div></div></a>' +
                            '<div class="check_list_box"><span class="checkbox" lang="'+row.ID+'" data-receiptstatus="'+row.ReceiptStatus+'" ' +
                            'data-rmb="'+formatRMBPrice(row.PurchaseRMB)+'" data-usd="'+formatUSDPrice(row.PurchaseUSD)+'" data-styleNo="'+row.StyleNo+'" ' +
                            'data-style="'+row.Style+'" data-series="'+row.Series+'" data-certType="'+row.CertType+'" data-Tag="'+row.Tag+'"' +
                            'data-wastage="'+row.Wastage+'" data-laborFee="'+row.LaborFee+'" data-sideLaborFee="'+row.SideLaborFee+'" ' +
                            'data-sidePrice="'+row.SidePrice+'" data-insurance="'+row.Insurance+'" data-technics="'+row.Technics+'"></span></div>' +
                            '</li>'
                        )
                    }

                    $("#inlaysettings").append(inlaysettings.join(''));

                    //懒加载
                    var n = 0,
                        imgNum = $("#inlaysettings li").length,
                        img = $('#inlaysettings li .product_img');
                    // myApp.initImagesLazyLoad(img)
                    $$('div.lazy').trigger('lazy');

                    //图片加载出来时居中显示 放在 framework.js

                    $(".image_app_box .product_img").load(function () {
                        //图片加载出来时居中显示  产品图 成品
                        var w = $(this).width();
                        var h = $(this).height();
                        var docu_w = $(window).width();
                        if (docu_w > 760) {
                            var screenW = 244;
                        } else {
                            var screenW = docu_w / 2;
                        }
                        if (w > h) {
                            var w_scale = w / screenW;
                            var now_h = h / w_scale;
                            var pa_top = screenW / 2 - now_h / 2;
                            $(this).css({
                                "width": "100%",
                                "padding-top": pa_top + "px",
                                "padding-bottom": pa_top + "px"
                            });
                        } else if (h > w) {
                            var h_scale = h / screenW;
                            var now_w = w / h_scale;
                            var pa_left = screenW / 2 - now_w / 2;
                            $(this).css({
                                "height": "100%",
                                "padding-left": pa_left + "px",
                                "padding-right": pa_left + "px"
                            });
                        } else {
                            $(this).css({
                                "height": "100%",
                                "width": "100%"
                            });
                        }

                    });
                }
                currentShow();  //币种设置
                console.info(new Date().getTime() - dtRenderStart + "ms");
                loads=true;
            } else {
                myApp.alert(res.msginfo);
            }
            myApp.hideIndicator();//隐藏加载中



        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            myApp.hideIndicator();//隐藏加载中
            var isLogin=getcookie("CustomerID");
            if(isLogin==null || isLogin=="(null)" ||!isLogin || isLogin=='nil'){
                myApp.alert("未搜索到相关数据");
            }else{
                myApp.alert("网络超时,请重试");

            }
        },
    });
}

//没权限返回的价格
function returnPrice(data){
	//if(data.Price || data.Price==0){
		return '<span class="CurrentRMB">￥<b title="价格">'+formatRMBPrice(data.Price)+'</b></span>';		
	//}else{
	//	return '<span style="font-size:14px;">￥<b title="价格">权限不足</b></span>';	
	//}
}


//显示现货或者定制的图片
function isStockImg(val){
	if(val==1){//现货
		return '<img src="../images/Coods_in_stock.svg" alt=""/>'
	}
	if(val==2){//定制
		return '<img src="../images/Customized.svg" alt=""/>'
	}
}
//优先显示简称
function ConvertSupplier(data) {
//	if(data.Supplier != undefined) {
//		if(data.ShortName != "") {
//			return data.ShortName;
//		} else {
			return data.Supplier;
//		}
//	} else
//		return "-";
}



//返回图片链接
function imgSrc(images) {
    if (images) {
        images = images.split('|');
        var small = images[0];
        var big = small.replace('400x400', '1920x1920');
        return small;
    }
    return '../images/no_img.jpg';//无图时返回默认图片
}





